package com.cyh.structurealgorithm;

import java.util.Arrays;

public class QuickSort {
    public static void test() {
        int arr[] = {3, 9, -1, 10, -2, 5, 10, 3, 11, -8, -2};
        quicksort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    public static void quicksort(int[] arr, int left, int right) {
        int l = left; //左下标
        int r = right; //右下标
        int pivot = arr[(left + right) / 2]; //中轴数
        int temp = 0;
        while (l < r) {
            while(arr[l] < pivot) {
                l += 1; //找到左边的数 > pivot
            }

            while(arr[r] > pivot) {
                r -= 1; //找到右边的数 < pivot
            }

            if(l >= r) {
                break; //左右两边的值符合条件了
            }
            temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;

            if(arr[l] == pivot) {
                r -= 1;
            }

            if(arr[r] == pivot) {
                l += 1;
            }
        }

        if(l == r) {
            l += 1;
            r -= 1;
        }

        if(left < r) {
            quicksort(arr, left, r);
        }

        if(right > l) {
            quicksort(arr, l, right);
        }

    }
}
